import 'dart:convert';
import 'package:intl/intl.dart';
import 'package:flutter/material.dart';

// 孕期信息主模型
class PregnancyInfo {
  int? id;
  final int userId;
  final DateTime lastPeriodDate;
  final DateTime? estimatedDueDate;
  final DateTime? confirmedPregnancyDate;
  final String pregnancyStatus;
  final String? conceptionMethod;
  int? currentWeek;
  int? currentDay;
  final String? pregnancyType;
  final String? notes;
  final DateTime createdAt;
  DateTime updatedAt;

  PregnancyInfo({
    this.id,
    required this.userId,
    required this.lastPeriodDate,
    this.estimatedDueDate,
    this.confirmedPregnancyDate,
    this.pregnancyStatus = 'ongoing',
    this.conceptionMethod,
    this.currentWeek,
    this.currentDay,
    this.pregnancyType = 'singleton',
    this.notes,
    required this.createdAt,
    required this.updatedAt,
  });

  // 计算当前孕周
  void updateCurrentWeek() {
    final now = DateTime.now();
    final daysSinceLMP = now.difference(lastPeriodDate).inDays;
    currentWeek = (daysSinceLMP / 7).floor();
    currentDay = daysSinceLMP % 7;
    updatedAt = DateTime.now();
  }

  // 计算预产期（基于末次月经，默认280天）
  DateTime calculateDueDate() {
    return lastPeriodDate.add(Duration(days: 280));
  }

  // 获取剩余天数
  int get daysRemaining {
    final dueDate = estimatedDueDate ?? calculateDueDate();
    return dueDate.difference(DateTime.now()).inDays;
  }

  // 获取怀孕进度百分比
  double get progressPercentage {
    const totalDays = 280;
    final daysElapsed = DateTime.now().difference(lastPeriodDate).inDays;
    return (daysElapsed / totalDays * 100).clamp(0, 100);
  }

  // 转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'user_id': userId,
      'last_period_date': DateFormat('yyyy-MM-dd').format(lastPeriodDate),
      'estimated_due_date': estimatedDueDate != null
          ? DateFormat('yyyy-MM-dd').format(estimatedDueDate!)
          : null,
      'confirmed_pregnancy_date': confirmedPregnancyDate != null
          ? DateFormat('yyyy-MM-dd').format(confirmedPregnancyDate!)
          : null,
      'pregnancy_status': pregnancyStatus,
      'conception_method': conceptionMethod,
      'current_week': currentWeek,
      'current_day': currentDay,
      'pregnancy_type': pregnancyType,
      'notes': notes,
      'created_at': createdAt.toIso8601String(),
      'updated_at': updatedAt.toIso8601String(),
    };
  }

  // 从Map创建
  factory PregnancyInfo.fromMap(Map<String, dynamic> map) {
    return PregnancyInfo(
      id: map['id'],
      userId: map['user_id'],
      lastPeriodDate: DateTime.parse(map['last_period_date']),
      estimatedDueDate: map['estimated_due_date'] != null
          ? DateTime.parse(map['estimated_due_date'])
          : null,
      confirmedPregnancyDate: map['confirmed_pregnancy_date'] != null
          ? DateTime.parse(map['confirmed_pregnancy_date'])
          : null,
      pregnancyStatus: map['pregnancy_status'],
      conceptionMethod: map['conception_method'],
      currentWeek: map['current_week'],
      currentDay: map['current_day'],
      pregnancyType: map['pregnancy_type'],
      notes: map['notes'],
      createdAt: DateTime.parse(map['created_at']),
      updatedAt: DateTime.parse(map['updated_at']),
    );
  }

  // 复制方法
  PregnancyInfo copyWith({
    int? id,
    int? userId,
    DateTime? lastPeriodDate,
    DateTime? estimatedDueDate,
    DateTime? confirmedPregnancyDate,
    String? pregnancyStatus,
    String? conceptionMethod,
    int? currentWeek,
    int? currentDay,
    String? pregnancyType,
    String? notes,
    DateTime? createdAt,
    DateTime? updatedAt,
  }) {
    return PregnancyInfo(
      id: id ?? this.id,
      userId: userId ?? this.userId,
      lastPeriodDate: lastPeriodDate ?? this.lastPeriodDate,
      estimatedDueDate: estimatedDueDate ?? this.estimatedDueDate,
      confirmedPregnancyDate: confirmedPregnancyDate ?? this.confirmedPregnancyDate,
      pregnancyStatus: pregnancyStatus ?? this.pregnancyStatus,
      conceptionMethod: conceptionMethod ?? this.conceptionMethod,
      currentWeek: currentWeek ?? this.currentWeek,
      currentDay: currentDay ?? this.currentDay,
      pregnancyType: pregnancyType ?? this.pregnancyType,
      notes: notes ?? this.notes,
      createdAt: createdAt ?? this.createdAt,
      updatedAt: updatedAt ?? this.updatedAt,
    );
  }
}

// 胎儿发育信息
class FetalDevelopment {
  final int week;
  final String sizeDescription;
  final String weightDescription;
  final double sizeInCm;
  final double weightInGrams;
  final List<String> keyDevelopments;
  final String commonSymptoms;
  final String recommendations;
  final String imageAssetName;
  final String comparisonDescription;

  FetalDevelopment({
    required this.week,
    required this.sizeDescription,
    required this.weightDescription,
    required this.sizeInCm,
    required this.weightInGrams,
    required this.keyDevelopments,
    required this.commonSymptoms,
    required this.recommendations,
    required this.imageAssetName,
    required this.comparisonDescription,
  });

  // 转换为Map
  Map<String, dynamic> toMap() {
    return {
      'week': week,
      'size_description': sizeDescription,
      'weight_description': weightDescription,
      'size_in_cm': sizeInCm,
      'weight_in_grams': weightInGrams,
      'key_developments': jsonEncode(keyDevelopments),
      'common_symptoms': commonSymptoms,
      'recommendations': recommendations,
      'image_asset_name': imageAssetName,
      'comparison_description': comparisonDescription,
    };
  }

  // 从Map创建
  factory FetalDevelopment.fromMap(Map<String, dynamic> map) {
    return FetalDevelopment(
      week: map['week'],
      sizeDescription: map['size_description'],
      weightDescription: map['weight_description'],
      sizeInCm: map['size_in_cm'],
      weightInGrams: map['weight_in_grams'],
      keyDevelopments: List<String>.from(jsonDecode(map['key_developments'])),
      commonSymptoms: map['common_symptoms'],
      recommendations: map['recommendations'],
      imageAssetName: map['image_asset_name'],
      comparisonDescription: map['comparison_description'],
    );
  }
}

// 产检记录
class PrenatalVisit {
  int? id;
  final int userId;
  final DateTime visitDate;
  final int weekOfPregnancy;
  final String doctorName;
  final String hospitalName;
  final String visitType;
  final String? bloodPressure;
  final double? weight;
  final double? fundalHeight;
  final int? fetalHeartRate;
  final String? urineTestResults;
  final String? bloodTestResults;
  final String? ultrasoundResults;
  final String? nextVisitDate;
  final String? doctorNotes;
  final String? motherNotes;
  final List<String>? medications;
  final List<String>? prescribedTests;

  PrenatalVisit({
    this.id,
    required this.userId,
    required this.visitDate,
    required this.weekOfPregnancy,
    required this.doctorName,
    required this.hospitalName,
    required this.visitType,
    this.bloodPressure,
    this.weight,
    this.fundalHeight,
    this.fetalHeartRate,
    this.urineTestResults,
    this.bloodTestResults,
    this.ultrasoundResults,
    this.nextVisitDate,
    this.doctorNotes,
    this.motherNotes,
    this.medications,
    this.prescribedTests,
  });

  // 转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'user_id': userId,
      'visit_date': DateFormat('yyyy-MM-dd').format(visitDate),
      'week_of_pregnancy': weekOfPregnancy,
      'doctor_name': doctorName,
      'hospital_name': hospitalName,
      'visit_type': visitType,
      'blood_pressure': bloodPressure,
      'weight': weight,
      'fundal_height': fundalHeight,
      'fetal_heart_rate': fetalHeartRate,
      'urine_test_results': urineTestResults,
      'blood_test_results': bloodTestResults,
      'ultrasound_results': ultrasoundResults,
      'next_visit_date': nextVisitDate,
      'doctor_notes': doctorNotes,
      'mother_notes': motherNotes,
      'medications': medications != null ? jsonEncode(medications!) : null,
      'prescribed_tests': prescribedTests != null ? jsonEncode(prescribedTests!) : null,
    };
  }

  // 从Map创建
  factory PrenatalVisit.fromMap(Map<String, dynamic> map) {
    return PrenatalVisit(
      id: map['id'],
      userId: map['user_id'],
      visitDate: DateTime.parse(map['visit_date']),
      weekOfPregnancy: map['week_of_pregnancy'],
      doctorName: map['doctor_name'],
      hospitalName: map['hospital_name'],
      visitType: map['visit_type'],
      bloodPressure: map['blood_pressure'],
      weight: map['weight'],
      fundalHeight: map['fundal_height'],
      fetalHeartRate: map['fetal_heart_rate'],
      urineTestResults: map['urine_test_results'],
      bloodTestResults: map['blood_test_results'],
      ultrasoundResults: map['ultrasound_results'],
      nextVisitDate: map['next_visit_date'],
      doctorNotes: map['doctor_notes'],
      motherNotes: map['mother_notes'],
      medications: map['medications'] != null
          ? List<String>.from(jsonDecode(map['medications']))
          : null,
      prescribedTests: map['prescribed_tests'] != null
          ? List<String>.from(jsonDecode(map['prescribed_tests']))
          : null,
    );
  }

  // 复制方法
  PrenatalVisit copyWith({
    int? id,
    int? userId,
    DateTime? visitDate,
    int? weekOfPregnancy,
    String? doctorName,
    String? hospitalName,
    String? visitType,
    String? bloodPressure,
    double? weight,
    double? fundalHeight,
    int? fetalHeartRate,
    String? urineTestResults,
    String? bloodTestResults,
    String? ultrasoundResults,
    String? nextVisitDate,
    String? doctorNotes,
    String? motherNotes,
    List<String>? medications,
    List<String>? prescribedTests,
  }) {
    return PrenatalVisit(
      id: id ?? this.id,
      userId: userId ?? this.userId,
      visitDate: visitDate ?? this.visitDate,
      weekOfPregnancy: weekOfPregnancy ?? this.weekOfPregnancy,
      doctorName: doctorName ?? this.doctorName,
      hospitalName: hospitalName ?? this.hospitalName,
      visitType: visitType ?? this.visitType,
      bloodPressure: bloodPressure ?? this.bloodPressure,
      weight: weight ?? this.weight,
      fundalHeight: fundalHeight ?? this.fundalHeight,
      fetalHeartRate: fetalHeartRate ?? this.fetalHeartRate,
      urineTestResults: urineTestResults ?? this.urineTestResults,
      bloodTestResults: bloodTestResults ?? this.bloodTestResults,
      ultrasoundResults: ultrasoundResults ?? this.ultrasoundResults,
      nextVisitDate: nextVisitDate ?? this.nextVisitDate,
      doctorNotes: doctorNotes ?? this.doctorNotes,
      motherNotes: motherNotes ?? this.motherNotes,
      medications: medications ?? this.medications,
      prescribedTests: prescribedTests ?? this.prescribedTests,
    );
  }
}

// 孕期症状记录
class PregnancySymptom {
  int? id;
  final int userId;
  final DateTime date;
  final String symptomName;
  final int severity;
  final String description;
  final String? notes;

  PregnancySymptom({
    this.id,
    required this.userId,
    required this.date,
    required this.symptomName,
    required this.severity, // 1-5 分级
    required this.description,
    this.notes,
  });

  // 获取症状严重程度颜色
  Color get severityColor {
    switch (severity) {
      case 1: return Colors.green;
      case 2: return Colors.lightGreen;
      case 3: return Colors.yellow;
      case 4: return Colors.orange;
      case 5: return Colors.red;
      default: return Colors.grey;
    }
  }

  // 获取严重程度描述
  String get severityDescription {
    switch (severity) {
      case 1: return '轻微';
      case 2: return '较轻';
      case 3: return '中等';
      case 4: return '较重';
      case 5: return '严重';
      default: return '未知';
    }
  }

  // 转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'user_id': userId,
      'date': DateFormat('yyyy-MM-dd').format(date),
      'symptom_name': symptomName,
      'severity': severity,
      'description': description,
      'notes': notes,
    };
  }

  // 从Map创建
  factory PregnancySymptom.fromMap(Map<String, dynamic> map) {
    return PregnancySymptom(
      id: map['id'],
      userId: map['user_id'],
      date: DateTime.parse(map['date']),
      symptomName: map['symptom_name'],
      severity: map['severity'],
      description: map['description'],
      notes: map['notes'],
    );
  }

  // 复制方法
  PregnancySymptom copyWith({
    int? id,
    int? userId,
    DateTime? date,
    String? symptomName,
    int? severity,
    String? description,
    String? notes,
  }) {
    return PregnancySymptom(
      id: id ?? this.id,
      userId: userId ?? this.userId,
      date: date ?? this.date,
      symptomName: symptomName ?? this.symptomName,
      severity: severity ?? this.severity,
      description: description ?? this.description,
      notes: notes ?? this.notes,
    );
  }
}

// 食物安全性信息
class FoodSafetyInfo {
  final int id;
  final String foodName;
  final String safetyStatus; // safe, caution, unsafe
  final String category;
  final String description;
  final String safetyExplanation;
  final List<String> alternatives;
  final String? preparationNotes;

  FoodSafetyInfo({
    required this.id,
    required this.foodName,
    required this.safetyStatus,
    required this.category,
    required this.description,
    required this.safetyExplanation,
    required this.alternatives,
    this.preparationNotes,
  });

  // 获取安全状态颜色
  Color get safetyColor {
    switch (safetyStatus) {
      case 'safe': return Colors.green;
      case 'caution': return Colors.amber;
      case 'unsafe': return Colors.red;
      default: return Colors.grey;
    }
  }

  // 获取安全状态描述
  String get safetyText {
    switch (safetyStatus) {
      case 'safe': return '可安全食用';
      case 'caution': return '谨慎食用';
      case 'unsafe': return '禁止食用';
      default: return '未知';
    }
  }

  // 转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'food_name': foodName,
      'safety_status': safetyStatus,
      'category': category,
      'description': description,
      'safety_explanation': safetyExplanation,
      'alternatives': jsonEncode(alternatives),
      'preparation_notes': preparationNotes,
    };
  }

  // 从Map创建
  factory FoodSafetyInfo.fromMap(Map<String, dynamic> map) {
    return FoodSafetyInfo(
      id: map['id'],
      foodName: map['food_name'],
      safetyStatus: map['safety_status'],
      category: map['category'],
      description: map['description'],
      safetyExplanation: map['safety_explanation'],
      alternatives: List<String>.from(jsonDecode(map['alternatives'])),
      preparationNotes: map['preparation_notes'],
    );
  }
}

// 孕期里程碑
class PregnancyMilestone {
  final int id;
  final int week;
  final String title;
  final String description;
  final List<String> thingsToKnow;
  final String imageAssetName;

  PregnancyMilestone({
    required this.id,
    required this.week,
    required this.title,
    required this.description,
    required this.thingsToKnow,
    required this.imageAssetName,
  });

  // 转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'week': week,
      'title': title,
      'description': description,
      'things_to_know': jsonEncode(thingsToKnow),
      'image_asset_name': imageAssetName,
    };
  }

  // 从Map创建
  factory PregnancyMilestone.fromMap(Map<String, dynamic> map) {
    return PregnancyMilestone(
      id: map['id'],
      week: map['week'],
      title: map['title'],
      description: map['description'],
      thingsToKnow: List<String>.from(jsonDecode(map['things_to_know'])),
      imageAssetName: map['image_asset_name'],
    );
  }
}

// 胎动记录
class FetalMovementRecord {
  int? id;
  final int userId;
  final DateTime date;
  final String time;
  final int movementCount;
  final String movementType;
  final String? notes;

  FetalMovementRecord({
    this.id,
    required this.userId,
    required this.date,
    required this.time,
    required this.movementCount,
    required this.movementType,
    this.notes,
  });

  // 转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'user_id': userId,
      'date': DateFormat('yyyy-MM-dd').format(date),
      'time': time,
      'movement_count': movementCount,
      'movement_type': movementType,
      'notes': notes,
    };
  }

  // 从Map创建
  factory FetalMovementRecord.fromMap(Map<String, dynamic> map) {
    return FetalMovementRecord(
      id: map['id'],
      userId: map['user_id'],
      date: DateTime.parse(map['date']),
      time: map['time'],
      movementCount: map['movement_count'],
      movementType: map['movement_type'],
      notes: map['notes'],
    );
  }

  // 复制方法
  FetalMovementRecord copyWith({
    int? id,
    int? userId,
    DateTime? date,
    String? time,
    int? movementCount,
    String? movementType,
    String? notes,
  }) {
    return FetalMovementRecord(
      id: id ?? this.id,
      userId: userId ?? this.userId,
      date: date ?? this.date,
      time: time ?? this.time,
      movementCount: movementCount ?? this.movementCount,
      movementType: movementType ?? this.movementType,
      notes: notes ?? this.notes,
    );
  }
}

// 孕期健康数据
class PregnancyHealthData {
  int? id;
  final int userId;
  final DateTime date;
  final double weight;
  final String? bloodPressure;
  final int? heartRate;
  final String? glucoseLevel;
  final String? sleepHours;
  final String? activityLevel;
  final String? notes;

  PregnancyHealthData({
    this.id,
    required this.userId,
    required this.date,
    required this.weight,
    this.bloodPressure,
    this.heartRate,
    this.glucoseLevel,
    this.sleepHours,
    this.activityLevel,
    this.notes,
  });

  // 转换为Map
  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'user_id': userId,
      'date': DateFormat('yyyy-MM-dd').format(date),
      'weight': weight,
      'blood_pressure': bloodPressure,
      'heart_rate': heartRate,
      'glucose_level': glucoseLevel,
      'sleep_hours': sleepHours,
      'activity_level': activityLevel,
      'notes': notes,
    };
  }

  // 从Map创建
  factory PregnancyHealthData.fromMap(Map<String, dynamic> map) {
    return PregnancyHealthData(
      id: map['id'],
      userId: map['user_id'],
      date: DateTime.parse(map['date']),
      weight: map['weight'],
      bloodPressure: map['blood_pressure'],
      heartRate: map['heart_rate'],
      glucoseLevel: map['glucose_level'],
      sleepHours: map['sleep_hours'],
      activityLevel: map['activity_level'],
      notes: map['notes'],
    );
  }

  // 复制方法
  PregnancyHealthData copyWith({
    int? id,
    int? userId,
    DateTime? date,
    double? weight,
    String? bloodPressure,
    int? heartRate,
    String? glucoseLevel,
    String? sleepHours,
    String? activityLevel,
    String? notes,
  }) {
    return PregnancyHealthData(
      id: id ?? this.id,
      userId: userId ?? this.userId,
      date: date ?? this.date,
      weight: weight ?? this.weight,
      bloodPressure: bloodPressure ?? this.bloodPressure,
      heartRate: heartRate ?? this.heartRate,
      glucoseLevel: glucoseLevel ?? this.glucoseLevel,
      sleepHours: sleepHours ?? this.sleepHours,
      activityLevel: activityLevel ?? this.activityLevel,
      notes: notes ?? this.notes,
    );
  }
}

// 常用孕期症状列表
List<String> commonPregnancySymptoms = [
  '孕吐',
  '疲劳',
  '乳房胀痛',
  '尿频',
  '情绪波动',
  '便秘',
  '头晕',
  '食欲改变',
  '恶心',
  '腹胀',
  '腰背痛',
  '头痛',
  '失眠',
  '水肿',
  '皮肤变化',
  '味觉变化',
  '鼻塞',
  '牙龈出血',
  '心悸',
  '胎动频繁',
  '胎动减少',
];

// 食物分类
List<String> foodCategories = [
  '水果',
  '蔬菜',
  '肉类',
  '海鲜',
  '乳制品',
  '坚果',
  '谷物',
  '豆类',
  '调味品',
  '饮料',
  '其他',
];